package com.myapp.ruyixing.ui;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.Volley;
import com.myapp.ruyixing.Config;
import com.myapp.ruyixing.R;
import com.myapp.ruyixing.http.RYHttpClient;
import com.myapp.ruyixing.http.RYHttpResponseHandler;
import com.myapp.ruyixing.model.NearbyStores;
import com.myapp.ruyixing.model.NearbyStores.Store;
import com.myapp.ruyixing.ui.widget.TitleBar;
import com.myapp.ruyixing.utils.BitmapLruCache;
import com.myapp.ruyixing.utils.UIUtils;

public class SearchShopListActivity extends Activity implements
		OnItemClickListener {

	private ShopListAdapter mAdapter;
	private List<Store> mShopList;
	private ListView mListView;

	private RYHttpResponseHandler mHttpResponseHandler = new RYHttpResponseHandler() {

		@Override
		public void onSuccess(Object o) {
			try {
				NearbyStores nearbyStores = (NearbyStores) o;
				onLoadingDataFinished(true, nearbyStores);
			} catch (Exception e) {
				onLoadingDataFinished(false, null);
			}
		}

		@Override
		public void onFailure(Throwable throwable) {
			onLoadingDataFinished(false, null);
		}
	};

	public static void startShopListActivity(Context context, String shopname) {
		if (context == null || TextUtils.isEmpty(shopname)) {
			return;
		}
		Intent intent = new Intent(context, SearchShopListActivity.class);
		intent.putExtra("shopname", shopname);
		context.startActivity(intent);
	}

	private void showToast(String msg) {
		Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
	}

	private void onLoadingDataStarted(String cityid, String shopname, int pn,
			int rn, double lat, double lon) {
		((TitleBar) findViewById(R.id.title_bar)).showLoading(true);
		RYHttpClient.getSearchShopList(this, mHttpResponseHandler, cityid,
				shopname, lat, lon);
	}

	private void onLoadingDataFinished(boolean succeed,
			NearbyStores nearbyStores) {
		((TitleBar) findViewById(R.id.title_bar)).showLoading(false);
		if (succeed && nearbyStores != null) {
			if (nearbyStores.items != null && nearbyStores.items.size() > 0) {
				mShopList.clear();
				mShopList.addAll(nearbyStores.items);
				mAdapter.notifyDataSetChanged();
			} else {
				showToast("搜索结果为空！");
			}
		} else {
			showToast("搜索失败！");
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search_shop_list);
		((TitleBar) findViewById(R.id.title_bar))
				.setOnIconClickedListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						onBackPressed();
					}
				});

		String shopname = getIntent().getStringExtra("shopname");
		if (TextUtils.isEmpty(shopname)) {
			finish();
			return;
		}
		// ((TextView) findViewById(R.id.location)).setText(Config.sMyLocation
		// .getStreet());
		((TextView) findViewById(R.id.location)).setVisibility(View.GONE);
		((TitleBar) findViewById(R.id.title_bar)).setTitleText("商户列表 ["
				+ shopname + "]");

		mListView = (ListView) findViewById(R.id.list);
		mShopList = new ArrayList<Store>();
		mAdapter = new ShopListAdapter(mShopList);
		mListView.setAdapter(mAdapter);
		mListView.setOnItemClickListener(this);
		onLoadingDataStarted(Config.sCityId, shopname, 0, 10,
				Config.sMyLocation.getLatitude(),
				Config.sMyLocation.getLongitude());
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long id) {
		if (id >= 0 && mShopList != null && id < mShopList.size()) {
			ShopDetailActivity.startShopDetailActivity(this,
					mShopList.get((int) id).merchant_id);
		}
	}

	private class ShopListAdapter extends ArrayAdapter<NearbyStores.Store> {

		private RequestQueue mQueue;
		private ImageLoader mImageLoader;

		private class ViewHolder {
			TextView mTitleView;
			TextView mPriceView;
			NetworkImageView mShopImage;
			TextView mDistanceView;

			ImageView mScoreView;
			TextView mLabelsView;
			View mCardIndicatorView;
			View mTicketIndicatorView;
			View mBenifitIndicatorView;
		}

		public ShopListAdapter(List<NearbyStores.Store> data) {
			super(SearchShopListActivity.this, -1, data);
			mQueue = Volley.newRequestQueue(SearchShopListActivity.this);
			mImageLoader = new ImageLoader(mQueue, new BitmapLruCache());
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = LayoutInflater.from(SearchShopListActivity.this).inflate(
						R.layout.shop_list_item, parent, false);

				ViewHolder holder = new ViewHolder();
				holder.mTitleView = (TextView) convertView
						.findViewById(R.id.text_shop_name);
				holder.mPriceView = (TextView) convertView
						.findViewById(R.id.text_average_cost);
				holder.mShopImage = (NetworkImageView) convertView
						.findViewById(R.id.image_shop);
				holder.mDistanceView = (TextView) convertView
						.findViewById(R.id.text_distance);
				holder.mScoreView = (ImageView) convertView
						.findViewById(R.id.score);
				holder.mLabelsView = (TextView) convertView
						.findViewById(R.id.text_keywords);
				holder.mCardIndicatorView = convertView
						.findViewById(R.id.img_ka);
				holder.mTicketIndicatorView = convertView
						.findViewById(R.id.img_quan);
				holder.mBenifitIndicatorView = convertView
						.findViewById(R.id.img_hui);

				convertView.setTag(holder);
			}

			ViewHolder mHolder = (ViewHolder) convertView.getTag();

			NearbyStores.Store item = getItem(position);

			mHolder.mTitleView.setText(item.merchant_name);
			int price = 0;
			try {
				price = Integer.parseInt(item.price);
			} catch (Exception e) {
			}
			mHolder.mPriceView.setText(getString(R.string.store_price, ""
					+ price));
			mHolder.mLabelsView.setText(item.keywords);
			mHolder.mScoreView.setImageLevel(item.score);
			long sDistance = item.distance;
			String picurl = item.picurl;

			if (sDistance >= 0) {
				String distance = "";
				if (sDistance >= 1000) {
					if (sDistance >= 1000000) {
						distance = "999+km";
					} else {
						distance = String.format("%.1fkm",
								((double) sDistance) / 1000);
					}
				} else {
					distance = sDistance + "m";
				}
				mHolder.mDistanceView.setText(distance);
			}

			if (!TextUtils.isEmpty(picurl)) {
				mHolder.mShopImage.setImageUrl(picurl, mImageLoader);
			}

			UIUtils.setViewVisibility(mHolder.mCardIndicatorView,
					"1".equals(item.card));
			UIUtils.setViewVisibility(mHolder.mTicketIndicatorView,
					"1".equals(item.ticket));
			UIUtils.setViewVisibility(mHolder.mBenifitIndicatorView,
					"1".equals(item.benefit));

			return convertView;

		}
	}

}
